package com.it.commicity.service.impl.sms;

import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.it.commicity.common.Result;
import com.it.commicity.common.ResultCodeEnum;
import com.it.commicity.config.exception.SmsException;
import com.it.commicity.service.sms.SmsService;
import com.it.commicity.utils.CodeUtil;
import com.it.commicity.utils.RedisConstants;
import com.it.commicity.utils.RegexUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    SmsService smsService;
    @Autowired
    private Client client;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void sendSMSCode(String phone, String code) {
        SendSmsRequest smsRequest = new SendSmsRequest();
        smsRequest.setPhoneNumbers(phone);
        smsRequest.setTemplateCode("SMS_154950909");
        smsRequest.setTemplateParam("{\"code\":\"" + code + "\"}");
        smsRequest.setSignName("阿里云短信测试");
        try {
            client.sendSms(smsRequest);
        } catch (Exception e) {
            throw new SmsException(ResultCodeEnum.SMS_SEND_ERROR);
        }
    }

    @Override
    public Result getSMSCode(String phone) {
        // 1.校验手机号
        if (RegexUtils.isPhoneInvalid(phone)) {
            // 2.如果不符合，返回错误信息
            throw new SmsException(ResultCodeEnum.CODE_PHONE_ERROR);
        }
        //生成四位验证码
        String code = CodeUtil.getRandomCode(4);
        //创建存入验证码到redis的key
        String key = RedisConstants.LOGIN_CODE_KEY + phone;
        //判断是否存在验证码
        Boolean hasKey = stringRedisTemplate.hasKey(key);
        if (hasKey) {
            //若存在，获取key的ttl
            Long ttl = stringRedisTemplate.getExpire(key, TimeUnit.SECONDS);
            //RedisConstants.LOGIN_CODE_TTL-ttl=保存时间-剩余时间=已保存时间
            //如果小于60s（我的key保存时间是180天）就相当于还未保存到60s，
            if (RedisConstants.LOGIN_CODE_TTL - ttl < 300L) {
                //验证法发送过于频繁
                throw new SmsException(ResultCodeEnum.SEND_SMS_TOO_OFTEN);
            }
        }
        //不存在，则保存并发送验证码,为了节约钱，保存15552000秒=180天
        stringRedisTemplate.opsForValue().set(key, code, RedisConstants.LOGIN_CODE_TTL, TimeUnit.SECONDS);
        smsService.sendSMSCode(phone, code);
        System.out.println("SmsServiceImpl->验证码发送成功");
        return Result.success("验证码发送成功");
    }
}
